import { NOT_LOADED, LOADING_SOURCE_CODE, NOT_BOOTSTRAPPED } from '../application/app.helpers.js';

// 将扁平化的数组转换为 Promise
function flatterArrayToPromise(fns) {
    fns = Array.isArray(fns) ? fns : [fns];

    return function (props) {
        return fns.reduce((rPromise, fn) => {
            return rPromise.then(() => fn(props))
        }, Promise.resolve())
    }
}


export function toLoadPromise(app) {

    return Promise.resolve().then(() => {

        // NOT_LOADED 是初始状态--用来拦截--有意义
        if (app.status !== NOT_LOADED) {
            // 应用加载完毕了
            return app;
        }
        // 也有意义
        app.status = LOADING_SOURCE_CODE; // 设置应用状态为加载中

        return app.loadApp(app.customProps).then(v => {

            const { bootstrap, mount, unmount } = v;
            // 加载完
            app.status = NOT_BOOTSTRAPPED; //  资源加载完毕 需要启动 此时还没启动
            app.bootstrap = flatterArrayToPromise(bootstrap);
            app.mount = flatterArrayToPromise(mount);
            app.unmount = flatterArrayToPromise(unmount);
            return app;
        })
    })
}